package com.example.coursedesign.ui.dashboard;

import android.app.Application;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.coursedesign.R;
import com.example.coursedesign.ui.dashboard.dao.ScienceDao;
import com.example.coursedesign.ui.dashboard.dao.ScienceLikeDao;
import com.example.coursedesign.ui.dashboard.entity.Science;

public class ScienceDetail extends AppCompatActivity {

    private TextView articleTitleTextView;
    private TextView articlePublishedTimeTextView;
    private TextView articleReadCountTextView;
    private ImageView articleImageView;
    private TextView articleContentTextView;
    private ImageButton favoriteButton;
    private TextView favoriteText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.science_detail);

        // 启用返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        // 初始化视图组件
        initViews();

        // 从Intent中获取文章ID和账户信息（假设账户信息已经通过某种方式传递过来）
        int scienceId = getIntent().getIntExtra("science_id", -1);
        String account = "user123"; // 这里需要替换为实际的用户账户信息

        // 执行异步任务时传入 int 类型的参数
        new LoadScienceTask().execute(scienceId);

        // 检查并设置收藏按钮初始状态
        checkAndSetFavoriteStatus(scienceId, account);

        // 设置收藏按钮点击监听器
        setupFavoriteButtonClickListener(scienceId, account);
    }

    private void initViews() {
        articleTitleTextView = findViewById(R.id.articleTitle);
        articlePublishedTimeTextView = findViewById(R.id.articlePublishedTime);
        articleReadCountTextView = findViewById(R.id.articleReadCount);
        articleImageView = findViewById(R.id.articleImage);
        articleContentTextView = findViewById(R.id.articleContent);
        favoriteButton = findViewById(R.id.favoriteButton);
        favoriteText = findViewById(R.id.food_favoriteText);
    }

    private class LoadScienceTask extends AsyncTask<Integer, Void, Science> {

        @Override
        protected Science doInBackground(Integer... params) {
            int id = params[0];
            Science science = new ScienceDao().getScienceById(id);
            if (science != null) {
                // 增加阅读量并更新数据库
                science.incrementReadCount();
                new ScienceDao().updateReadCount(id, science.getRead_count());
            }
            return science;
        }

        @Override
        protected void onPostExecute(Science science) {
            if (science != null) {
                // 更新UI
                updateUI(science);
            } else {
                // 如果找不到对应的文章，可以考虑展示错误信息或结束Activity
                finish();
            }
        }
    }

    private void updateUI(Science science) {
        articleTitleTextView.setText(science.getTitle());

        // 使用 SimpleDateFormat 格式化时间（如果需要）
        articlePublishedTimeTextView.setText("发布时间：" + science.getPublish_time());

        articleReadCountTextView.setText("阅读量：" + science.getRead_count());

        // 使用Glide加载图片，假设image字段包含Base64编码的字符串或网络图片URL
        Glide.with(this)
                .load(science.getImage())
                .into(articleImageView);

        articleContentTextView.setText(science.getContent()); // 假设Science对象有getContent()方法
    }

    // 切换收藏按钮状态的方法
    private void toggleFavoriteIcon(boolean isFavorited) {
        if (isFavorited) {
            favoriteButton.setImageResource(R.drawable.ic_like_filled); // 收藏后的图标
            favoriteText.setText("已收藏");
        } else {
            favoriteButton.setImageResource(R.drawable.ic_favorite); // 未收藏的图标
            favoriteText.setText("收藏");
        }
    }

    // 检查并设置收藏按钮初始状态
    private void checkAndSetFavoriteStatus(int scienceId, String account) {
        ScienceLikeDao scienceLikeDao = new ScienceLikeDao(new Application());
        scienceLikeDao.isFavorited(scienceId, account, new ScienceLikeDao.OnFavoritedListener() {
            @Override
            public void onFavoritedResult(boolean isFavorited) {
                runOnUiThread(() -> toggleFavoriteIcon(isFavorited));
            }

            @Override
            public void onError(String errorMessage) {
                Log.e("ScienceDetail", "检查收藏状态失败: " + errorMessage);
                runOnUiThread(() -> toggleFavoriteIcon(false));
            }
        });
    }

    // 处理收藏操作
    private void setupFavoriteButtonClickListener(final int scienceId, final String account) {
        favoriteButton.setOnClickListener(v -> {
            ScienceLikeDao scienceLikeDao = new ScienceLikeDao(getApplicationContext());

            scienceLikeDao.isFavorited(scienceId, account, new ScienceLikeDao.OnFavoritedListener() {
                @Override
                public void onFavoritedResult(boolean isFavorited) {
                    if (isFavorited) {
                        // 如果已收藏，则取消收藏
                        scienceLikeDao.removeFavorite(scienceId, account, new ScienceLikeDao.OnOperationCompleteListener() {
                            @Override
                            public void onOperationComplete(boolean success) {
                                if (success) {
                                    runOnUiThread(() -> toggleFavoriteIcon(false));
                                }
                            }
                            @Override
                            public void onError(String errorMessage) {
                                Log.e("ScienceDetail", "取消收藏失败: " + errorMessage);
                            }
                        });
                    } else {
                        // 如果未收藏，则添加收藏
                        scienceLikeDao.addFavorite(scienceId, account, new ScienceLikeDao.OnOperationCompleteListener() {
                            @Override
                            public void onOperationComplete(boolean success) {
                                if (success) {
                                    runOnUiThread(() -> toggleFavoriteIcon(true));
                                }
                            }
                            @Override
                            public void onError(String errorMessage) {
                                Log.e("ScienceDetail", "添加收藏失败: " + errorMessage);
                            }
                        });
                    }
                }

                @Override
                public void onError(String errorMessage) {
                    Log.e("ScienceDetail", "检查收藏状态失败: " + errorMessage);
                }
            });
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        setResult(AppCompatActivity.RESULT_OK); // 设置返回结果
        finish(); // 结束当前活动并返回上一个活动
        return true;
    }

    @Override
    public void onBackPressed() {
        setResult(AppCompatActivity.RESULT_OK); // 设置返回结果
        super.onBackPressed(); // 返回上一个 Activity
    }
}